package com.hdl.servlet.cart;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hdl.entity.CartItem;
import com.hdl.entity.MallCart;

/**
 * 提交前的购物车数据修改
 * @author Administrator
 *
 */
@WebServlet("/updateCart.let")
public class UpdateCartServlet extends HttpServlet{
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//获取参数  用户可能对数量进行了修改
		String[] ids = req.getParameterValues("uid");
		String[] nums = req.getParameterValues("num");
		
		//从session中获取购物车
		MallCart cart = (MallCart) req.getSession().getAttribute("cart");
		int num = 0;//标记
		for (String id : ids) {
			Map<String, CartItem> map = cart.getProductMap();
			if(map.containsKey(id)) {
				CartItem item = map.get(id);
				item.setNum(Integer.valueOf(nums[num]));//更新数量
				item.setTotal(item.getProduct().getMallProductPrice1() * Integer.valueOf(nums[num]));//更新小计价格
//				System.out.println("更新后"+item.getProduct().getMallProductName()+":"+item.getTotal());
			}
		}
		int mallCartTotal = 0;
		Set<String> keySet = cart.getProductMap().keySet();
		for (String key : keySet) {
			CartItem Item = cart.getProductMap().get(key);
			mallCartTotal += Item.getProduct().getMallProductPrice1() * Item.getNum();
		}
		cart.setMallCartTotal(mallCartTotal);//更新计算总计
//		System.out.println(cart.getMallCartTotal());
		
		//把更新后的购物车存入session
		req.getSession().setAttribute("cart", cart);
		
		//重定向
		resp.sendRedirect(req.getContextPath()+"/address.let");
		
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

}
